package com.jiantong.web.open.app.work;

import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.service.BreedFactoryReadService;
import com.jiantong.web.core.enums.ExceptionCode;
import com.jiantong.work.model.OtherPurchaseRecord;
import com.jiantong.work.service.OtherPurchaseRecordReadService;
import com.jiantong.work.service.OtherPurchaseRecordWriteService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Strings;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * Created by niufei on 2017/4/10.
 * 其它购买记录
 */
@Slf4j
@OpenBean
public class OtherPurchaseRecordApis {

    @RpcConsumer
    private OtherPurchaseRecordReadService otherPurchaseRecordReadService;

    @RpcConsumer
    private OtherPurchaseRecordWriteService otherPurchaseRecordWriteService;

    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;

    @OpenMethod(
            key = "find.other.purchase.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public OtherPurchaseRecord findOtherPurchaseRecordById(Long id){
        if (id == null ){
            log.error("is should be not null");
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"is should be not null");
        }
        Response<OtherPurchaseRecord> response = otherPurchaseRecordReadService.findOtherPurchaseRecordById(id);
        if(!response.isSuccess()){
            log.error("failed to find OtherPurchaseRecord , cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    @OpenMethod(
            key = "paging.other.purchase",
            paramNames = {"pageNo","pageSize","breedFactoryId","status"},
            httpMethods = RequestMethod.GET
    )
    public Paging<OtherPurchaseRecord> pagingOtherPurchaseRecordFarm(Integer pageNo, Integer pageSize ,Long breedFactoryId, Integer status){
        if (breedFactoryId == null){
            log.error("breedFactoryId is should be not null");
            throw  new OPServerException(ExceptionCode.PARAMETER_NOT_EXIST.value(),"breedFactoryId is should be not null");
        }
        Response<Paging<OtherPurchaseRecord>> response = otherPurchaseRecordReadService.pagingOtherPurchaseRecordsFarm(pageNo,pageSize,breedFactoryId,status);
        if(!response.isSuccess()){
            log.error("failed to paging OtherPurchase farm, cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    @OpenMethod(
            key = "paging.status.other.purchase",
            paramNames = {"pageNo","pageSize","breedFactoryId","breedType","fromDate","toDate"},
            httpMethods = RequestMethod.GET
    )
    public Paging<OtherPurchaseRecord> pagingOtherPurchaseRecordGov(Integer pageNo , Integer pageSize , Long breedFactoryId ,Integer breedType, String fromDate , String toDate){
        Date start = null;
        if (!Strings.isNullOrEmpty(fromDate)) {
            start = DateTime.parse(fromDate).toDate();
        }

        Date end = null;
        if (!Strings.isNullOrEmpty(toDate)) {
            end = DateTime.parse(toDate).toDate();
        }
        Response<Paging<OtherPurchaseRecord>> response = otherPurchaseRecordReadService.pagingOtherPurchaseRecordsGov(pageNo , pageSize ,breedFactoryId,breedType,start,end);

        if(!response.isSuccess()){
            log.error("failed to paging OtherPurchaseRecord gov, cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    @OpenMethod(
            key = "create.other.purchase",
            paramNames = {"otherPurchase","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Map<String , Object> createOtherPurchaseRecord(OtherPurchaseRecord otherPurchaseRecord , Integer toStatus){
        LoginUser loginUser = UserUtil.getCurrentUser();
        BreedFactory breedFactory = breedFactoryReadService.findById(loginUser.getOrganizationId()).getResult();
        if(breedFactory.getIsScale() != 1){
            log.error("this is san hu");
            throw new OPClientException(ExceptionCode.DATA_NOT_FOUND.value(),"this is san hu");
        }
        Response<Map<String , Object>> response = otherPurchaseRecordWriteService.create(otherPurchaseRecord, toStatus);
        if (!response.isSuccess()){
            log.error("failed to create otherPurchaseRecord error = {}, cause : {}", otherPurchaseRecord, response.getError());
            throw new OPServerException(ExceptionCode.DATA_WRITE_FAIL.value(),response.getError());
        }
        return response.getResult();
    }


    @OpenMethod(
            key = "update.other.purchase",
            paramNames = {"otherPurchase","toStatus"},
            httpMethods = RequestMethod.PUT
    )
    public Map<String , Object> updateOtherPurchaseRecord(OtherPurchaseRecord otherPurchaseRecord , Integer toStatus){
        if(otherPurchaseRecord.getId() == null){
            log.error("failed to update otherPurchase error = {}, cause : {}", otherPurchaseRecord,otherPurchaseRecord.getId());
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"otherPurchase.id.is.null");
        }
        Response<Map<String , Integer>> mapResponse =  otherPurchaseRecordReadService.findStatusById(otherPurchaseRecord.getId());
        if(mapResponse.isSuccess() && !mapResponse.getResult().get("status").equals(otherPurchaseRecord.getStatus())){
            log.error("otherPurchase is already submitted error = {}, cause : {}", otherPurchaseRecord.getStatus(),mapResponse.getResult().get("status"));
            throw new OPClientException(ExceptionCode.DATA_NOT_FOUND.value(),"this.report.is.already.submitted");
        }

        Response<Map<String , Object>> response = otherPurchaseRecordWriteService.update(otherPurchaseRecord,toStatus);
        if(!response.isSuccess()){
            if(!response.isSuccess()){
                log.error("failed to update otherPurchase error = {}, cause : {}", otherPurchaseRecord, response.getError());
                throw new OPServerException(ExceptionCode.DATA_UPDATE_FAIL.value(),response.getError());
            }
        }
        return response.getResult();
    }
}
